package net.yunxinyong.sign.service.impl;

import com.google.common.collect.Lists;
import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.CecBaseMapper;
import net.yunxinyong.sign.mapper.CecThreeMapper;
import net.yunxinyong.sign.mapper.EcnomicInventoryMapper;
import net.yunxinyong.sign.service.CecBaseService;
import net.yunxinyong.sign.service.CecOneService;
import net.yunxinyong.sign.service.CecThreePlatformService;
import net.yunxinyong.sign.service.CecThreeService;
import net.yunxinyong.sign.utils.ListUtils;
import net.yunxinyong.sign.vo.CecThreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecThreeServiceImpl implements CecThreeService {
    @Autowired
    private CecThreeMapper cecThreeMapper;
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private CecThreePlatformService cecThreePlatformService;
    @Autowired
    private CecBaseMapper cecBaseMapper;
    @Autowired
    private CecBaseService cecBaseService;
    @Autowired
    private CecOneService cecOneService;

    @Override
    public void insertOrUpdate(CecThreeVo cecThreeVo) {
        Date date = new Date();
        if(cecThreeVo.getId() == null){
            cecThreeVo.setCreateTime(date);
            cecThreeVo.setUpdateTime(date);
            cecThreeVo.setStatus(0);
            //只有 提交的时候才进行表间的逻辑审核，暂存，不进行表间逻辑审核。
            if (cecThreeVo.getState() != null && cecThreeVo.getState() == 1){
                //3表和1表的表间关系审核  611-1表经营性单位收入>=301营业收入，不大于10%
                threeAndOneLogic(cecThreeVo);
                baseAndThreeLogic2(cecThreeVo);
            }
            //这个方法是base表和3表关于住宿餐饮业 营业面积和营业额的关系,同时往3表插入数据的时候同时往base表添加数据 , 这个表间关系也是只有base表已经是提交状态的时候，才会发生。
            Integer update = baseAndThreeLogic1(cecThreeVo);
            int i = cecThreeMapper.insertSelective(cecThreeVo);
            Integer id = cecThreeVo.getId();
            if(i <= 0 || update <= 0 ){
                throw new CECException(501,"企业信息添加失败");
            }
            List<CecThreePlatform> brancesList = cecThreeVo.getBrancesList();
            if(!ListUtils.isEmpty(brancesList)){
                for(CecThreePlatform brances : brancesList){
                    cecThreePlatformService.insert(brances,id);
                }
            }
        }else {
            cecThreeVo.setUpdateTime(date);
            //只有 提交的时候才进行表间的逻辑审核，暂存，不进行表间逻辑审核。
            if (cecThreeVo.getState() != null && cecThreeVo.getState() == 1){
                //3表和1表的表间关系审核  611-1表经营性单位收入>=301营业收入，不大于10%
                threeAndOneLogic(cecThreeVo);
                baseAndThreeLogic2(cecThreeVo);
            }
            //这个方法是base表和3表关于住宿餐饮业 营业面积和营业额的关系，同时往3表插入数据的时候同时往base表添加数据, 这个表间关系也是只有base表已经是提交状态的时候，才会发生。
            Integer update = baseAndThreeLogic1(cecThreeVo);
            int i = cecThreeMapper.updateByPrimaryKey(cecThreeVo);
            Integer threeId = cecThreeVo.getId();
            if(i <= 0 || update <= 0){
                throw new CECException(501,"企业信息更新失败");
            }
        }
    }


    @Override
    public CecThreeVo get(Integer invId) {
        CecThreeExample cecThreeExample = new CecThreeExample();
        cecThreeExample.createCriteria().andInvIdEqualTo(invId).andStatusEqualTo(0);
        List<CecThree> cecThreeList = cecThreeMapper.selectByExample(cecThreeExample);
        CecThreeVo cecThreeVo = new CecThreeVo();
        CecBaseExample cecBaseExample = new CecBaseExample();
        cecBaseExample.createCriteria().andInvIdEqualTo(invId).andStatusEqualTo(0);
        List<CecBase> cecBaseList = cecBaseMapper.selectByExample(cecBaseExample);
        if (!ListUtils.isEmpty(cecBaseList)){
            cecThreeVo.setMajorType(cecBaseList.get(0).getMajorType());
        }
        if(!ListUtils.isEmpty(cecThreeList)){
            BeanUtils.copyProperties(cecThreeList.get(0),cecThreeVo);
            return cecThreeVo;
        }else {
            return null;
        }
    }

    /**
     *  往3表添加数据的时候，同时往base表添加193项数据
     * @param cecThreeVo
     * @return
     */
    public Integer baseAndThreeLogic1(CecThreeVo cecThreeVo){
        CecBase cecBase = cecBaseService.select(cecThreeVo.getInvId());
        if (cecBase != null){

            //base 表数据
            //`business_income` decimal(20,5) DEFAULT NULL COMMENT '(193)营业收入(单位：千元)',
            //  `total_assets` decimal(20,5) DEFAULT NULL COMMENT '(193)资产总计(单位：千元)',
            //  `tax_and_additional` decimal(20,5) DEFAULT NULL COMMENT '(193)税金及附加(单位：千元)',
            //3表数据
            // `business_income` decimal(20,2) DEFAULT NULL COMMENT '(301)营业收入 ',
            //`total_assets` decimal(20,2) DEFAULT NULL COMMENT '(213)资产总计 '
            //`taxation` decimal(20,2) DEFAULT NULL COMMENT '(309)税金及附加 '
            cecBase.setBusinessIncome(cecThreeVo.getBusinessIncome());
            cecBase.setTotalAssets(cecThreeVo.getTotalAssets());
            cecBase.setTaxAndAdditional(cecThreeVo.getTaxation());
            return cecBaseMapper.updateByPrimaryKeySelective(cecBase);
        }else {
            throw new CECException(502,"请先填写611表");
        }
    }

    /**
     * 3表和base表的表间逻辑
     * @param cecThreeVo
     */
    public void baseAndThreeLogic2(CecThreeVo cecThreeVo){
        CecBase cecBase = cecBaseService.select(cecThreeVo.getInvId());
        if (cecBase != null ) {
            //04其中：零售额>0，则611表E03批发和零售业年末零售营业面积>0
            //10 餐费收入>0，则611表S03住宿和餐饮业年末餐饮营业面积>0
            if (cecThreeVo.getRetailSales() != null && cecThreeVo.getRetailSales().compareTo(new BigDecimal(0)) > 0) {
                if (cecBase.getWarOperatingArea() != null && cecBase.getWarOperatingArea() <= 0) {
                    throw new CECException(502, "611-3表第04项 其中：零售额>0，则611表E03批发和零售业年末零售营业面积>0,请改写611表");
                }
            }
            if (cecThreeVo.getMealIncome() != null && cecThreeVo.getMealIncome().compareTo(new BigDecimal(0)) > 0) {
                if (cecBase.getAacOperatingArea() != null && cecBase.getAacOperatingArea() <= 0) {
                    throw new CECException(502, "611-3表第10项 餐费收入>0，则611表S03住宿和餐饮业年末餐饮营业面积>0,请改写611表");
                }
            }
            // 611-3表      611表E02仅选2030 网上商店时：（611-3表通过公共网络实现的零售额/04其中：零售额 ）>0.5
            String retailFormat = "2030";
            if (cecBase.getRetailFormat() != null && retailFormat.equals(cecBase.getRetailFormat())) {
                if (cecThreeVo.geteRetailSales() != null && cecThreeVo.getRetailSales() != null && cecThreeVo.geteRetailSales().divide(cecThreeVo.getRetailSales(), 2, RoundingMode.HALF_UP).doubleValue() < 0.5) {
                    throw new CECException(502, "您在611表的E02项天选择的是 2030网上商店，则您在611-3表中 批发业和零售业经营情况中的 通过公共网络实现的零售额 应大于 04项 零售额 的50%");
                }
            }
        } else {
            throw new CECException(502, "请先填写611表");
        }

    }
    /**
     * 一表和3表的逻辑。 611-1表产业收入之和（支出）>=法人财务数据，不大于10%(611-1表经营性单位收入>=301营业收入，不大于10%)
     * @param cecThreeVo
     */
    public void threeAndOneLogic(CecThreeVo cecThreeVo) {
        EcnomicInventoryExample ecnomicInventoryExample = new EcnomicInventoryExample();
        ecnomicInventoryExample.createCriteria().andIdEqualTo((long)cecThreeVo.getInvId());
        List<EcnomicInventory> ecnomicInventories = ecnomicInventoryMapper.selectByExample(ecnomicInventoryExample);
        if (!ListUtils.isEmpty(ecnomicInventories)){
            EcnomicInventory ecnomicInventory = ecnomicInventories.get(0);
            //如果企业的类型是包含 1表，再进行判断， 这样做视为了防止 企业在 提交base表 之后 填写了部分的表 重新修改表类型，这时新分配的表是不包含 1表的。
            if (ecnomicInventory.getType() != null && ecnomicInventory.getType().contains("1")){
                List<CecOne> cecOneList = cecOneService.get(cecThreeVo.getInvId());
                if(!ListUtils.isEmpty(cecOneList)){
                    //计算611-1表经营性单位收入 （这个收入是本部和分支机构经营收入的总和）
                    BigDecimal oneBussineseIncome = new BigDecimal(0);
                    for (CecOne cecOne : cecOneList){
                        if (cecOne.getBussineseIncome() != null && !cecOne.getBussineseIncome().equals("")){
                            BigDecimal bigDecimal = new BigDecimal(cecOne.getBussineseIncome());
                            oneBussineseIncome = bigDecimal.add(oneBussineseIncome);
                        }
                    }
                    boolean logic = !(cecThreeVo.getBusinessIncome() != null && oneBussineseIncome.compareTo(cecThreeVo.getBusinessIncome()) >= 0) || !(cecThreeVo.getBusinessIncome() != null && cecThreeVo.getBusinessIncome().multiply(new BigDecimal(1.1)).compareTo(oneBussineseIncome) >= 0);
                    if (logic){
                        throw new CECException(502,"您填写的数据有误，您在611-1表中填写的11项经营性单位收入（这个收入是指本部和分支机构经营收入的总和） 应该 大于等于 3表301项营业收入，并且不超过3表301项的10%");
                    }
                }
            }
        }
    }
}
